package com.hhhn.wk.main.tab4;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.login.LoginActivity;
import com.hhhn.wk.main.tab4.abuot.AboutActivity;
import com.hhhn.wk.main.tab4.pwd.SetPayPwdActivity;
import com.hhhn.wk.main.tab4.pwd.UpPwdActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.dialog.ClassifyMessageFenXiang;
import com.hhhn.wk.widget.versionsup.up.ApkUtils;
import com.hhhn.wk.widget.versionsup.up.SDCardUtils;
import com.hhhn.wk.widget.versionsup.updataservice.UpdataService;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import static com.hhhn.wk.utils.AllPublic.isLogin;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/2 0002    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 设置
 * * * * * * * * * * * */
public class SettingActivity extends BaseActivity implements ClassifyMessageFenXiang.OnClassifyMessageFenXiang, DialogInterface.OnCancelListener{
    private static String APPNAMEname= "hhhn.apk";//app名字
    private PackageInfo packInfo;
    private String versionname;
    private int versioncode;
    User user=null;
    private LinearLayout ll_uppwd;//修改密码
    private LinearLayout ll_setpaypwd;//修改支付密码
    private LinearLayout ll_about;//关于我们
    private LinearLayout ll_update;//关于我们
    private LinearLayout ll_er;//二维码
    private LinearLayout ll_share;//分享
    private TextView tv_title;//标题
    private TextView tv_versionname;//当前版本信息
    private Context context;
    private BaseActivity activity;
    private Button btn_esc;//退出登录

    UMWeb web=null;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_setting);
        context=SettingActivity.this;
        activity=this;
    }
    @Override
    protected void initView() {
        ll_setpaypwd=findViewById(R.id.ll_setpaypwd);
        btn_esc=findViewById(R.id.btn_esc);
        tv_title=findViewById(R.id.tv_title);
        ll_uppwd=findViewById(R.id.ll_uppwd);
        ll_about=findViewById(R.id.ll_about);
        ll_update=findViewById(R.id.ll_update);
        tv_versionname=findViewById(R.id.tv_versionname);
        ll_er=findViewById(R.id.ll_er);
        ll_share=findViewById(R.id.ll_share);
    }
    @Override
    protected void initData() {
        tv_title.setText("设置中心");
        PackageManager packageManager = context.getPackageManager();
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionname = packInfo.versionName;
            versioncode = packInfo.versionCode;
            tv_versionname.setText(versionname);
            System.out.println("#$%%$##$%%$##$%^%$#$%#$%$$%=="+versionname+"=="+packInfo.versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ;
        }
        user = (User) SharePreferencesUser.getBean(activity,Constants.USER);
        if (user!=null){
            int isLogin = user.getIsLogin();
            if (isLogin==2){
                btn_esc.setVisibility(View.VISIBLE);
            }else {
                btn_esc.setVisibility(View.GONE);
            }
        }else {
            btn_esc.setVisibility(View.GONE);
        }
    }
    @Override
    protected void initClick() {
        ll_uppwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(context,UpPwdActivity.class);
                startActivityForResult(intent,1);
            }
        });
        ll_setpaypwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin(context, (BaseActivity) context)) {
                    Intent intent=new Intent(context,SetPayPwdActivity.class);
                    startActivityForResult(intent,0);//0未设置过  1已设置过
                }
            }
        });

        ll_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            startActivity(new Intent(context,AboutActivity.class));
            }
        });
        ll_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkUpdata();
            }
        });
        btn_esc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePreferencesUser.getclear(activity,"user");
                //登出
                MobclickAgent.onProfileSignOff();
                sendBR();
                sendBR2();
                finish();
            }
        });
        ll_er.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AllPublic.linkH5(context,activity,"二维码",Constants.ERCODE);
            }
        });
        ll_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClassifyMessageFenXiang.showSheet(SettingActivity.this,SettingActivity.this,SettingActivity.this);
            }
        });
    }

//    private UMShareListener umShareListener = new UMShareListener() {
//        /**
//         * @descrption 分享开始的回调
//         * @param platform 平台类型
//         */
//        @Override
//        public void onStart(SHARE_MEDIA platform) {
//
//        }
//
//        /**
//         * @descrption 分享成功的回调
//         * @param platform 平台类型
//         */
//        @Override
//        public void onResult(SHARE_MEDIA platform) {
//            Toast.makeText(SettingActivity.this,"成功了",Toast.LENGTH_LONG).show()；
//        }
//
//        /**
//         * @descrption 分享失败的回调
//         * @param platform 平台类型
//         * @param t 错误原因
//         */
//        @Override
//        public void onError(SHARE_MEDIA platform, Throwable t) {
//            Toast.makeText(SettingActivity.this,"失败"+t.getMessage(),Toast.LENGTH_LONG).show();
//        }
//
//        /**
//         * @descrption 分享取消的回调
//         * @param platform 平台类型
//         */
//        @Override
//        public void onCancel(SHARE_MEDIA platform) {
//            Toast.makeText(SettingActivity.this,"取消了",Toast.LENGTH_LONG).show();
//
//        }
//    };
    public void sendBR2(){
        activity. LogWk("购物车成功发送广播");
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiverCart);
        activity. sendBroadcast(intent);
    }
    /**
     * 1.链接服务器
     */
    private void checkUpdata() {
        showLoad();
        RequestParams params = AllPublic.getParamsVersion(activity, "/getVersion", false);
        Log.d("@", "checkUpdata: "+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogWk("版本更新：" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("0".equals(jsonObject.getString("code"))) {
                        JSONObject version = jsonObject.getJSONObject("data");
                        String appDownUrl = "";
                        appDownUrl = version.has("versionApk") ? version.getString("versionApk") : "";//下载地址
                        String apkVersionName = version.has("versionNum") ? version.getString("versionNum") : "";//版本号Name
                        int apkVersionCode = version.has("versionCode") ? version.getInt("versionCode") : 0;//版本号Code
                        int mandatoryUpdate = version.has("versionForce") ? version.getInt("versionForce") : 0;//是否强制更新   1强制
                        String updateContent = version.has("versionExplain") ? version.getString("versionExplain") : "";//
//                        //下载地址
//        String appDownUrl = "https://pro-app-tc.fir.im/cab8f4e80d4c0f177302f1c33de55aaf9284e27b.apk?sign=f2eac1a36160c3beb5609ae339096ff2&t=5a698653";
//                        //版本号Name
//        String apkVersionName = "v3.0.0";
////                        //版本号Code
//        int apkVersionCode = 6;
////                        //是否强制更新
//        int mandatoryUpdate = 1;
//                        //更新日志
//        String updateContent = "1.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "2.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "3.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "4.开发中开发中开发中开发中开发中开发中开发中！";
                        getMyApp().setAPKDOWNURL(appDownUrl);
                        getMyApp().setAPPNAMEAZ(apkVersionName + "hhhn.apk");
                        APPNAMEname = apkVersionName + "hhhn.apk";
                        if (apkVersionCode > versioncode) {
                            LogWk(appDownUrl);
                            showDialog(context, appDownUrl, apkVersionName, mandatoryUpdate, updateContent);
                        } else {
                            Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
                        dismissLoad();
                    } else {
                        Toast.makeText(context, jsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();
                        dismissLoad();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismissLoad();
                }
                dismissLoad();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                dismissLoad();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }

            @Override
            public void onFinished() {
                dismissLoad();
            }
        });
    }
    /**
     * 2弹出新版本提示
     */
    public static void showDialog(final Context context,
                                  final String updataUrl,
                                  final String apkVersionName,
                                  final int mandatoryUpdate,
                                  final String updateContent) {
        final Dialog dialog = new AlertDialog.Builder(context).create();
        final File file = new File(SDCardUtils.getRootDirectory() + UpdataService.DOWNLOADPATH + new UpdataService(APPNAMEname));
        dialog.setCancelable(true);// 可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);//
        dialog.show();
        View view = LayoutInflater.from(context).inflate(R.layout.up_version_update_dialog, null);
        dialog.setContentView(view);
        final Button btnOk = (Button) view.findViewById(R.id.btn_update_id_ok);
        Button btnCancel = (Button) view.findViewById(R.id.btn_update_id_cancel);
        TextView tvContent = (TextView) view.findViewById(R.id.tv_update_content);
        TextView tvUpdateTile = (TextView) view.findViewById(R.id.tv_update_title);
        final TextView tvUpdateMsgSize = (TextView) view.findViewById(R.id.tv_update_msg_size);
        tvUpdateTile.setText("最新版本：" + apkVersionName);
        tvContent.setText(Html.fromHtml(updateContent));
        if (mandatoryUpdate == 1) {
            btnCancel.setVisibility(View.GONE);
        }
        if (file.exists() && file.getName().equals(new UpdataService(APPNAMEname))) {
            tvUpdateMsgSize.setText("新版本已经下载，是否安装？");
            btnOk.setText("立即安装");
        } else {
//            tvUpdateMsgSize.setText("新版本大小：自定义版大小");
        }
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (v.getId() == R.id.btn_update_id_ok) {
                    //安装包存在已经下载---直接安装
                    if (file.exists() && file.getName().equals(new UpdataService(APPNAMEname))) {
                        Intent intent = ApkUtils.getInstallIntent(file);
                        context.startActivity(intent);
                    } else {
                        Toast.makeText(context, "下载中", Toast.LENGTH_SHORT).show();
                        //没有下载，则开启服务下载新版本
                        Intent intent = new Intent(context, UpdataService.class);
                        intent.putExtra("updataUrl", updataUrl);
                        context.startService(intent);
                    }
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    public void sendBR(){
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiver);
        sendBroadcast(intent);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            SharePreferencesUser.getclear(activity,"user");
            sendBR();
            startActivity(new Intent(context, LoginActivity.class));
            finish();
        }
    }
    /**
     * 分享弹窗接口回调
     * @param dialog
     */
    @Override
    public void onCancel(DialogInterface dialog) {
    }
    /**
     * 分享弹窗接口回调
     * * setPlatform  直接分享.share();
     *   setDisplayList  调起官方的面板  .open();
     */
    @Override
    public void onClick(int whichButton) {
        switch (whichButton) {
            case 1://微信
                if (!AllPublic.isWXAppInstalledAndSupported(context)){
                    ToastUtils.showShortToast(context,"请检查并安装微信最新版本");
                    return;
                }
                ShareWeb();
                new ShareAction(activity).withMedia(web).setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(umShareListener).share();
                break;
            case 2://微信
                if (!AllPublic.isWXAppInstalledAndSupported(context)){
                    ToastUtils.showShortToast(context,"请检查并安装微信最新版本");
                    return;
                }
                ShareWeb();
                new ShareAction(activity).withMedia(web).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(umShareListener).share();
                break;
            default:
                break;
        }
    }
    @Override
    protected void onResume() {
        dismissLoad();
        super.onResume();
    }
    private void ShareWeb(){
    UMImage thumb =  new UMImage(SettingActivity.this, R.mipmap.ic_logo);
    web = new UMWeb("http://www.huoniupifa.com/hn-web/appxz.html");
    web.setTitle("货惠·货牛，货惠万家、货牛批发！");//标题
    web.setThumb(thumb);  //缩略图
    web.setDescription("货惠·货牛，货惠万家、货牛批发！全国第一家综合性货物批发O2O县域经济网络平台，是面向全国商超门店进行货物批发采购和统一配送的应用平台。");//描述
    }
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
        }
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat","platform"+platform);
            Toast.makeText(context, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(context,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if(t!=null){
                Log.d("throw","throw:"+t.getMessage());
            }
        }
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(context,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };
}
